package org.parosproxy.paros.core.proxy.custom;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpRequestHeader;

public class CookieCleaner {

	private static CookieCleaner INSTANCE;
	private boolean enabled = false;
	private Set<String> cleanedCookies = new HashSet<String>();
	private final static Pattern domain = Pattern.compile("^(http[s]?://)?(www\\.)?(.*)$");

	private CookieCleaner() {
		enabled = true;
	}

	public static CookieCleaner getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new CookieCleaner();
		}
		return INSTANCE;
	}

	public boolean isClean(String method, String client, String host, HttpMessage headers) {
		if (method == "POST")
			return true;
		if (!enabled)
			return true;
		if (!hasCookies(headers.getRequestHeader()))
			return true;

		return cleanedCookies.contains(client + getDomainFor(host));
	}

	public List<String> getExpireHeaders(String method, String client, String host, HttpRequestHeader headers, String path) {
		String domain = getDomainFor(host);
		cleanedCookies.add(client + domain);

		List<String> expireHeaders = new ArrayList<String>();

		for (Object cookie : headers.getHeaders("cookie")) {
			for (String value : ((String) cookie).split(";")) {
				String data = value.split("=")[0].trim();
				List<String> expireHeadersForCookie = getExpireCookieStringFor(data, host, domain, path);
				expireHeaders.addAll(expireHeadersForCookie);
			}

		}

		return expireHeaders;
	}

	public boolean hasCookies(HttpRequestHeader headers) {
		boolean cookies = false;
		if (headers.getHeaders("cookie") != null) {
			cookies = headers.getHeaders("cookie").size() > 0;
		}
		return cookies;
	}

	public String getDomainFor(String host) {
		String[] hostParts = host.split("\\.");
		Matcher matcher = domain.matcher(host);
		if (matcher.matches()) {
			return "." + matcher.group(3);
		}
		return "." + hostParts[1] + "." + hostParts[2];
	}

	public List<String> getExpireCookieStringFor(String cookie, String host, String domain, String path) {
		String[] pathList = path.split("/");
		List<String> expireStrings = new ArrayList<String>();

		expireStrings.add(cookie + "=" + "EXPIRED;Path=/;Domain=" + domain + ";Expires=Mon, 01-Jan-1990 00:00:00 GMT\r\n");

		expireStrings.add(cookie + "=" + "EXPIRED;Path=/;Domain=" + host + ";Expires=Mon, 01-Jan-1990 00:00:00 GMT\r\n");

		if (pathList.length > 2) {
			expireStrings.add(cookie + "=" + "EXPIRED;Path=/" + pathList[1] + ";Domain=" + domain + ";Expires=Mon, 01-Jan-1990 00:00:00 GMT\r\n");

			expireStrings.add(cookie + "=" + "EXPIRED;Path=/" + pathList[1] + ";Domain=" + host + ";Expires=Mon, 01-Jan-1990 00:00:00 GMT\r\n");
		}

		return expireStrings;
	}
}
